package com.zenithmind.gateway.route;

import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.Builder;
import org.springframework.cloud.gateway.route.builder.GatewayFilterSpec;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 存储相关服务路由配置器
 * 专门负责磁盘服务、版本服务的路由配置
 * 遵循单一职责原则：只负责存储相关的路由配置
 */
@Slf4j
@Component
public class StorageRouteConfigurer implements RouteConfigurer {

    @Override
    public void configureRoutes(Builder routes) {
        log.info("配置存储相关服务路由...");
        
        // 磁盘服务路由 - 文件、文件夹、分享
        routes.route("disk-service-route", r -> r
            .path("/api/zenithMind/disk/**",
                 "/api/zenithMind/file/**",
                 "/api/zenithMind/folder/**",
                 "/api/zenithMind/share/**",
                 "/api/zenithMind/api/v1/disk/**")
            // 仅为API v1路径应用stripPrefix过滤器
            .filters(f -> pathFilterForApiV1(f, "/api/zenithMind/api/v1/"))
            .uri("lb://disk-service"));
        
        // 版本控制服务路由 - 代码仓库、提交、分支
        routes.route("version-service-route", r -> r
            .path("/api/zenithMind/version/**",
                 "/api/zenithMind/repository/**",
                 "/api/zenithMind/commit/**",
                 "/api/zenithMind/branch/**",
                 "/api/zenithMind/api/v1/repositories/**", 
                 "/api/zenithMind/api/v1/commits/**", 
                 "/api/zenithMind/api/v1/file-versions/**", 
                 "/api/zenithMind/api/v1/branches/**")
            // 仅为API v1路径应用stripPrefix过滤器
            .filters(f -> pathFilterForApiV1(f, "/api/zenithMind/api/v1/"))
            .uri("lb://version-service"));
    }

    @Override
    public String getConfigureName() {
        return "StorageRouteConfigurer";
    }

    @Override
    public int getOrder() {
        return 4;
    }
    
    /**
     * 路径过滤器工具方法 - 专用于/api/zenithMind/api/v1/前缀的路径
     * 如果路径以指定前缀开头，则移除前缀
     */
    private GatewayFilterSpec pathFilterForApiV1(GatewayFilterSpec f, String prefixPattern) {
        return f.rewritePath("/api/zenithMind/api/v1/(?<segment>.*)", "/api/zenithMind/${segment}");
    }
}
